/*
 * 跳转
 * type: 0，保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面。
 * type: 1，关闭当前页面，跳转到应用内的某个页面。
 * type: 2，关闭当前页面，返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈，决定需要返回几层。、
 * type: 3, 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
 * */
export function goto_url(url, type) {
	console.log('这是拿到的值', url, type)
	if (type == 0) {
		uni.navigateTo({
			url: url
		});
		// _this.$router.push(url);
	} else if (type == 1) {
		// _this.$router.replace(url);
		uni.redirectTo({
			url: url
		});
	} else if (type == 2) {
		uni.navigateBack({
			delta: url
		});
		// _this.$router.go(url);
	} else if (type == 3) {
		uni.switchTab({
			url: url
		})
	}
}
/*提示框*/
function toast(text, icon) {
	// console.log(icon)
	uni.showToast({
		title: text,
		icon: (icon == undefined ? 'none' : icon)
	})
}
const formatDateTime = date => {
	date = date ? new Date() : new Date(date.replace(/-/g, '/'));
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDateTimeTwo = date => {
	date = new Date(date);
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDateTimeThree = date => {
	date = new Date(date);
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [day].map(formatNumber).join('-') + '日'
}
const formatDateTimeParams = (date, arr = ['year', 'month', 'day'], arrt = []) => {
	date = new Date(date);
	let str
	let timeObj = {
		year: date.getFullYear(),
		month: date.getMonth() + 1,
		day: date.getDate(),
		hour: date.getHours(),
		minute: date.getMinutes(),
		second: date.getSeconds(),
	}
	let list = []
	arr.forEach(item => {
		list.push(timeObj[item])
	})

	str = list.map(formatNumber).join('-')

	if (arr[0] == 'day') {
		str += '日'
	}

	let listT = []
	if (arrt.length > 0) {
		arrt.forEach(item => {
			listT.push(timeObj[item])
		})
		str += ' '
		str += listT.map(formatNumber).join(':')
	}

	return str
}

const timeHowLong = (start, end) => {
	let cha = start > end ? start - end : end - start;
	let day = Math.floor(cha / (24 * 3600 * 1000));
	let hours = Math.floor(cha % (24 * 3600 * 1000) / (3600 * 1000));
	let minutes = Math.floor(cha % (24 * 3600 * 1000) % (3600 * 1000) / (60 * 1000));
	let seconds = Math.floor(cha % (24 * 3600 * 1000) % (3600 * 1000) % (60 * 1000) / 1000);

	let str = ''
	if (day) {
		str += `${day}天`
	} else if (hours) {
		str += `${hours}小时`
	} else if (minutes) {
		str += `${minutes}分钟`
	} else if (seconds) {
		str += `${seconds}秒`
	}
	return str
}
const formatTime = date => {
	date = new Date(date);
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [hour, minute, second].map(formatNumber).join(':')
}

const formatdate = date => {
	date = new Date(date);
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-');
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
/**
 * 根据key查找数据中对应的值
 */
const SearchData = (key, data) => {
	var value = '';
	var i = 0;
	while (i < data.length) {

		if (key == data[i].key) {
			value = data[i].title;
			break;
		} else {
			i++;
			continue;
		}
	}
	return value;
}

/**
 * 根据key查找数据中对应角标
 */
const SearchDataIndex = (key, data) => {
	var value = '';
	var i = 0;
	while (i < data.length) {

		if (key == data[i].key) {
			value = i;
			break;
		} else {
			i++;
			continue;
		}
	}
	return value;
}

//脱敏
const searchDataIndex = (data, left = 3, right = 4) => {
	let sLength = data.length || 0
	if (!data || sLength === 0) {
		return ''
	}

	if (sLength === 1) {
		return data[0] + '*'.repeat(sLength)
	}

	if (sLength <= left) {
		return data[0] + '*'.repeat(sLength - 1)
	}

	if (sLength <= left + right) {
		return data[0] + '*'.repeat(sLength - 2) + data[sLength - 1]
	}

	return data.slice(0, left) + '*'.repeat(sLength - right - left) + data.slice(sLength - right)
}

//计算结束时间
const computeEndDate = (date, type, num) => {
	let date_str = date.replace(new RegExp(/-/gm), '/');
	let new_date = new Date(date_str);
	let end_date;
	if (type == '分钟') { // 分钟
		end_date = new_date.getMinutes();
		new_date.setMinutes(end_date + parseFloat(num));
	} else { // 小时
		end_date = new_date.getHours();
		new_date.setHours(end_date + parseFloat(num));
	}
	return new_date;
}


/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
const parseTime = (time, cFormat) => {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string')) {
			if ((/^[0-9]+$/.test(time))) {
				// support "1548221490638"
				time = parseInt(time)
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), '/')
			}
		}

		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		return value.toString().padStart(2, '0')
	})
	return time_str
}

/**
 * 计算天数差的函数，通用
 * @param sDate1
 * @param sDate2
 * @returns {Number}天数
 */
const dateFullDiff = (sDate1, sDate2) => { // sDate1和sDate2是1970-01-01 00:00:00格式
	// console.log("dateFullDiff=", sDate1);
	// console.log("dateFullDiff=", sDate2);
	var d1 = new Date(sDate1.replace(new RegExp(/-/gm), '/'));
	var d2 = new Date(sDate2.replace(new RegExp(/-/gm), '/'));
	var dateSpan = parseInt(d2 - d1);

	//计算出相差天数
	var days = Math.floor(dateSpan / (24 * 3600 * 1000))
	//计算天数后剩余的毫秒数
	var leave1 = dateSpan % (24 * 3600 * 1000)
	var hours = Math.floor(leave1 / (3600 * 1000))
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000))
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000)

	var leave4 = dateSpan % (24 * 3600 * 3600 * 1000);
	var minutesAll = Math.floor(leave4 / (60 * 1000))

	return {
		days: days,
		hours: hours,
		minutes: minutes,
		seconds: seconds,
		minutesAll: minutesAll
	}
}

export default {
	goto_url,
	toast,
	formatDateTime,
	formatTime,
	formatdate,
	SearchData,
	searchDataIndex,
	formatDateTimeTwo,
	formatDateTimeThree,
	formatDateTimeParams,
	timeHowLong,
	computeEndDate,
	parseTime,
	dateFullDiff
}
